package com.hundsun.yr.universal.p2p.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.adapter.HolderAdapter;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper.UpdateItem;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.utils.MathUtils;
import com.hundsun.yr.universal.library.utils.SpannableStringBuilderUtils;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.library.widget.HSLoadMoreListView;
import com.hundsun.yr.universal.library.widget.HSLoadMoreListView.OnLoadMoreListener;
import com.hundsun.yr.universal.library.widget.HSSwipeRefreshLayout;
import com.hundsun.yr.universal.p2p.bean.MyInvestBeen;
import com.hundsun.yr.universal.p2p.bean.TradeRecord;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.WaitPayListPresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.MineInvestDetailActivity;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseFragment;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.view.base.BaseListView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * @version V1.0
 * @Title: WaitPayFragment.java
 * @Description: 我的投资-待支付
 * @date 2016-1-5 下午2:51:14
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class InHandFragment extends BaseFragment implements BaseListView, UpdateItem<MyInvestBeen>, OnLoadMoreListener,
        OnRefreshListener, OnItemClickListener {

    /**
     * 适配器
     **/
    private HolderAdapter<MyInvestBeen> mAdapter = null;
    /**
     * 上拉列表（listView）
     **/
    private HSLoadMoreListView lv_inhand = null;
    /**
     * 下拉容器
     **/
    private HSSwipeRefreshLayout hsSwipeRefreshLayout_inhand = null;

    /**
     * 数据集合
     **/
    private List<MyInvestBeen> data = new ArrayList<MyInvestBeen>();
    /**
     * 请求接口
     **/
    private RequestPresenter mPresenter = null;
    /**定时器容器**/
    /**
     * zwgt时间
     **/
    private String zwgt_data;

    /**
     * 最下面一条的position
     */
    private int lastVisiblePosition;

    /**
     * 最后一条的ctime
     */
    private Long time;
    private LayoutInflater mInflater;
    private RelativeLayout headerView;

    @Override
    protected void onFirstUserVisible() {
        // TODO Auto-generated method stub
        loadingData();
    }

    @Override
    protected void onUserVisible() {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onUserInvisible() {
        // TODO Auto-generated method stub

    }

    @Override
    protected View getLoadingTargetView() {
        // TODO Auto-generated method stub
        hsSwipeRefreshLayout_inhand = findView(R.id.hsSwipeRefreshLayout_inhand);
        return hsSwipeRefreshLayout_inhand;
    }

    @Override
    protected void initViewsAndEvents() {
        // TODO Auto-generated method stub
        if (mPresenter == null) {
            mPresenter = new WaitPayListPresenterImpl(mContext, this, TradeRecord.BASEKEY);
        }
        if (hsSwipeRefreshLayout_inhand == null) {
            hsSwipeRefreshLayout_inhand = (HSSwipeRefreshLayout) getActivity().findViewById(R.id.hsSwipeRefreshLayout_inhand);
        }
        lv_inhand = findView(R.id.lv_inhand);

        ViewCreatorHelper<MyInvestBeen> creatorHelper = new ViewCreatorHelper<MyInvestBeen>(R.layout.item_mine_invest_already, this);
        mAdapter = new HolderAdapter<MyInvestBeen>(mContext, creatorHelper.viewCreator());

        mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        headerView = (RelativeLayout) mInflater.inflate(R.layout.item_header_10dp, lv_inhand, false);
        lv_inhand.addHeaderView(headerView);

        lv_inhand.setAdapter(mAdapter);
        hsSwipeRefreshLayout_inhand.setOnRefreshListener(this);
        lv_inhand.setOnLoadMoreListener(this);
        lv_inhand.setOnItemClickListener(this);

    }

    /**
     * 加载数据
     */
    private void loadingData() {
        hsSwipeRefreshLayout_inhand.setRefreshing(true);
        mPresenter = new WaitPayListPresenterImpl(mContext, this, TradeRecord.BASEKEY);
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.INVERST_LIST, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.INVERST_LIST + "?type=" + 4,
                Constants.EVENT_REFRESH_DATA, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.INVERST_LIST + "?type=" + 4,
                        sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
    }

    @Override
    protected int getContentViewLayoutID() {
        // TODO Auto-generated method stub
        return R.layout.frag_mine_invest_inhand;
    }

    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {
    }

    @Override
    protected boolean isBindEventBusHere() {
        // TODO Auto-generated method stub
        return true;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> void refreshListData(List<T> result) {
        // TODO Auto-generated method stub
        hsSwipeRefreshLayout_inhand.setRefreshing(false);
        lv_inhand.setLoadMoreEnabled(true);
        if (data.size() > 0) data.clear();
        if (result != null) {
            data.addAll((Collection<? extends MyInvestBeen>) result);
        }
        mAdapter.update(data);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> void addMoreListData(List<T> result) {
        // TODO Auto-generated method stub
        lv_inhand.onLoadMoreComplete();

        if (result != null && result.size() > 0) {
            data.addAll((Collection<? extends MyInvestBeen>) result);
            lv_inhand.setLoadMoreEnabled(true);
        } else {
            lv_inhand.setLoadMoreEnabled(false);
        }
        mAdapter.update(data);
    }

    @Override
    public <T> void onFailure(String task_name) {
        // TODO Auto-generated method stub
        hsSwipeRefreshLayout_inhand.setRefreshing(false);
        lv_inhand.onLoadMoreComplete();
        if (data.size() > 0) data.clear();
        lv_inhand.setAdapter(mAdapter);
        mAdapter.update(data);
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        mPresenter = new WaitPayListPresenterImpl(mContext, this, TradeRecord.BASEKEY);
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.INVERST_LIST, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.INVERST_LIST + "?type=" + 4,
                Constants.EVENT_REFRESH_DATA, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.INVERST_LIST + "?type=" + 4,
                        sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
    }

    @Override
    public void onLoadMore() {
        // TODO Auto-generated method stub
        mPresenter = new WaitPayListPresenterImpl(mContext, this, TradeRecord.BASEKEY);

        lastVisiblePosition = lv_inhand.getLastVisiblePosition();
        time = Long.valueOf(data.get(lastVisiblePosition - 2).ctime);

        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.INVERST_LIST, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.INVERST_LIST + "?type=" + 4 + "&ctime=" + time,
                Constants.EVENT_LOAD_MORE_DATA, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.INVERST_LIST + "?type=" + 4 + "&ctime=" + time,
                        sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
    }

    @Override
    public void refreshItem(View view, int position, final MyInvestBeen invest) {
        /**年化收益**/
        TextView tv_annualincome = findView(view, R.id.tv_annualincome);
        SpannableStringBuilder spaBuilder = new SpannableStringBuilder();
        if (!invest.rate.isEmpty()) {
            spaBuilder = (SpannableStringBuilderUtils.sizeAndColorSpan
                    (CommTool.keep1Digits(invest.rate) + "%", "%", 14, mContext.getResources().getColor(R.color.cl_redformula_text_3837), true));
        } else {
            spaBuilder = (SpannableStringBuilderUtils.sizeAndColorSpan
                    ("0" + "%", "%", 14, mContext.getResources().getColor(R.color.cl_redformula_text_3837), true));
        }
        tv_annualincome.setText(spaBuilder);

        /**营销商品名称**/
        TextView tv_title = findView(view, R.id.tv_title);
        tv_title.setText(invest.name);

        /**累计收益**/
        TextView tv_income = findView(view, R.id.tv_income);

        try{
            // TODO: 2017/6/14 这边考虑服务端坑比的时候
            BigDecimal touZi = new BigDecimal(invest.true_amount);
            BigDecimal rate = new BigDecimal(invest.rate).divide(new BigDecimal(100),10,BigDecimal.ROUND_HALF_UP);
            BigDecimal term = new BigDecimal(invest.total_term);
            BigDecimal monthRate = rate.divide(new BigDecimal(12), 10, BigDecimal.ROUND_HALF_UP);

            BigDecimal expected_revenue = null;
            switch (invest.pay_method){
                case "1":
                    //到期还本息付
                    expected_revenue = touZi.multiply(rate).multiply(term).divide(new BigDecimal(360), 5, BigDecimal.ROUND_HALF_UP);
                    break;
                case "2":
                    //按月还息到期还本
                    expected_revenue = touZi.multiply(monthRate).multiply(term);
                    break;
                case "3":
                    //等额本息
                    BigDecimal pow = (monthRate.add(new BigDecimal(1))).pow(term.intValue());
                    expected_revenue = (touZi.multiply(monthRate).multiply(pow).divide(pow.subtract(new BigDecimal(1)), 10, BigDecimal.ROUND_HALF_UP)).multiply(term).subtract(touZi);
                    break;
                case "4":
                    //等额本金
                    expected_revenue = touZi.multiply(monthRate).multiply((term.add(new BigDecimal(1)))).divide(new BigDecimal(2), 10, BigDecimal.ROUND_HALF_UP);
                    break;
            }

            if (MathUtils.compare(invest.progress,"40") <= 0){
                tv_income.setText(SpannableStringBuilderUtils.sizeSpan(getString(R.string._yuan,CommTool.keep2Digits(expected_revenue + "")), getString(R.string.yuan), 14));
            } else {
                tv_income.setText(SpannableStringBuilderUtils.sizeSpan(getString(R.string._yuan,CommTool.keep2Digits(invest.total_income)), getString(R.string.yuan), 14));
            }
        }catch (Exception e){
            tv_income.setText("");
        }

        /**到期时间**/
        TextView tv_prd_progress = findView(view, R.id.tv_prd_progress);
        tv_prd_progress.setText(invest.getProgress(mContext));

        /**投资金额**/
        TextView tv_invsetmoney = findView(view, R.id.tv_invsetmoney);
        SpannableStringBuilder spaBuilder_investmoney = (SpannableStringBuilderUtils.colorSpan
                (getString(R.string._mineinvest_money, getString(R.string._yuan,CommTool.keep2Digits(invest.amount))), getString(R.string._yuan,CommTool.keep2Digits(invest.amount)), mContext.getResources().getColor(R.color.cl_redformula_text_3837)));
        tv_invsetmoney.setText(spaBuilder_investmoney);

        /**去支付**/
        HSButton btn_to_payment = findView(view, R.id.btn_to_payment);

        /**累计收益**/
        TextView ev_accumulate_income = findView(view, R.id.ev_accumulate_income);
        ev_accumulate_income.setText(getString(R.string.come_income));

        /**
         * orderprogress
         0	草稿
         10	已申请待付款
         15	银行处理中
         20	已付款
         30	计息中（暂时不用，同产品）
         50	已兑付（暂时不用，同产品）
         100	用户撤销
         110	超时关闭
         */

        /**
         *
         0	未发布	0：未发布
         10	投标中	1：投标中
         15	待放款	无
         18	放款中	无
         20	计息中	2：计息中
         30	待返还（暂时不用）	3：待返还
         40	已返还	4：已返还
         50	已结束	5：已结束
         60	已撤销	6：已结束
         100	逾期未返还
         105	逾期部分返还（暂不开发）
         110	逾期已返还
         120	流标
         125	停售（募集期截止但未募满）
         130	风控拒绝放款
         200	逾期已返还(与11重复废弃)
         */

        /**到期收益|还款进度**/
        TextView tv_incomemonet = findView(view, R.id.tv_incomemonet);
        SpannableStringBuilder spaBuilder_incomemonet = new SpannableStringBuilder();

        if (TextUtils.equals(invest.progress,"40")){
            spaBuilder_incomemonet = (SpannableStringBuilderUtils.colorSpan
                    (getString(R.string._investment_duration,invest.getTerm()), invest.getTerm(), mContext.getResources().getColor(R.color.cl_redformula_text_3837)));
            tv_incomemonet.setText(spaBuilder_incomemonet);
        } else {
            if (invest.repay_time != null && !invest.repay_time.isEmpty()){
                spaBuilder_incomemonet = (SpannableStringBuilderUtils.colorSpan
                        (getString(R.string.clear_date, invest.repay_time), invest.repay_time, mContext.getResources().getColor(R.color.cl_redformula_text_3837)));
                tv_incomemonet.setText(spaBuilder_incomemonet);
            } else {
                spaBuilder_incomemonet = (SpannableStringBuilderUtils.colorSpan
                        (getString(R.string.clear_date, invest.end_time), invest.end_time, mContext.getResources().getColor(R.color.cl_redformula_text_3837)));
                tv_incomemonet.setText(spaBuilder_incomemonet);
            }
        }
    }

    @Override
    public <T> void initializeViews(String task_name, T data) {
        // TODO Auto-generated method stub
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (isFastDoubleClick()){
            return;
        }
        if (position == 0 || position > data.size()) return;
        Bundle bundle = new Bundle();
        bundle.putSerializable(Extras.DATA, data.get(position - 1));
        readyGo(MineInvestDetailActivity.class, bundle);
    }

    /**
     * 防止按钮连续点击
     */
    private static long lastClickTime;
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if ( time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }
}
